package controllers

import (
	"NewEdu/models"
	"NewEdu/utils"
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"strings"

	beego "github.com/beego/beego/v2/server/web"
)

// 用户管理
type TUserController struct {
	beego.Controller
}

// URL映射
func (c *TUserController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
}

// 添加用户
// @Title 添加
// @Description 添加用户
// @Param	body		body 	models.TUser	true		"用户基本信息"
// @Param	Authorization	header	string	true	" Token"
// @Success 201 {int} models.TUser
// @Failure 403 body is empty
// @router /add [post]
func (c *TUserController) Post() {
	var v models.TUser
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		if _, err := models.AddTUser(&v); err == nil {
			c.Ctx.Output.SetStatus(201)
			c.Data["json"] = utils.Export(1000, "注册成功", &v)
		} else {
			c.Data["json"] = utils.Export(1001, "注册失败", err.Error())
		}
	} else {
		c.Data["json"] = utils.Export(1001, "注册失败", err.Error())
	}
	c.ServeJSON()
}

// 用户注册
// @Title 用户注册
// @Description 用户注册
// @Param	body		body 	models.TUser	true		"用户基本信息"
// @Success 201 {int} models.TUser
// @Failure 403 body is empty
// @router /register [post]
func (c *TUserController) Register() {
	var v models.TUser
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		if _, err := models.AddTUser(&v); err == nil {
			c.Ctx.Output.SetStatus(201)
			c.Data["json"] = utils.Export(1000, "注册成功", &v)
		} else {
			c.Data["json"] = utils.Export(1001, "注册失败", err.Error())
		}
	} else {
		c.Data["json"] = utils.Export(utils.CodeValidationFail, "注册失败", err.Error())
	}
	c.ServeJSON()
}

// 获取单个用户
// @Title 获取一个
// @Description 通过sn获取TUser
// @Param	sn		path 	string	true		"The key for staticblock"
// @Param	Authorization	header	string	true	" Token"
// @Success 200 {object} models.TUser
// @Failure 403 :id is empty
// @router /:sn [get]
func (c *TUserController) GetOne() {
	snStr := c.Ctx.Input.Param(":sn")
	v, err := models.GetTUserById(snStr)
	if err != nil {
		c.Data["json"] = utils.Export(1001, "获取失败", err.Error())
	} else {
		c.Data["json"] = utils.Export(1000, "获取成功", &v)
	}
	c.ServeJSON()
}

// 登录
// @Title 登录
// @Description 通过学号和密码登录
// @Param	sn		path 	string	true		"用学号登录"
// @Param	pswd		path 	string	true		"密码"
// @Success 200 {object} models.TUser
// @Failure 403 :id is empty
// @router /login/:sn/:pswd [get]
func (c *TUserController) Login() {
	snStr := c.Ctx.Input.Param(":sn")
	pswdStr := c.Ctx.Input.Param(":pswd")
	pswdStr = strings.Trim(pswdStr, " ")
	v, jwt, err := models.UserLogin(snStr, pswdStr)
	if err != nil {
		c.Data["json"] = utils.Export(1001, "登录失败", err.Error())
	} else {
		c.Data["json"] = utils.Export(1000, jwt, &v)
	}
	c.ServeJSON()
}

// 查询用户
// @Title 查询用户
// @Description 查询用户
// @Param	Authorization	header	string	true	" Token"
// @Param	name	query	string	false	"姓名"
// @Param	sn	query	string	false	"学号"
// @Param	tel	query	string	false	"电话"
// @Param	departid	query	int	false	"班级id"
// @Param	limit	query	string	false	"每页的条数"
// @Param	offset	query	string	false	"起始数"
// @Success 200 {object} models.TUser
// @Failure 403
// @router /query/class [get]
func (c *TUserController) QueryUser() {
	var query = make(map[string]string)
	name := c.GetString("name")
	sn := c.GetString("sn")
	tel := c.GetString("tel")
	departid, _ := c.GetInt("departid")
	limit, _ := c.GetInt64("limit")
	offset, _ := c.GetInt64("offset")

	if len(name) > 0 {
		query["name__icontains"] = name
	}
	if len(sn) > 0 {
		query["sn"] = sn
	}
	if len(tel) > 0 {
		query["tel"] = tel
	}
	if departid > 0 {
		query["t_depart_id"] = strconv.Itoa(departid)
	}

	l, err := models.GetAllTUser(query, nil, nil, nil, offset, limit)
	if err != nil {
		c.Data["json"] = utils.Export(1001, "查询失败", err.Error())
	} else {
		c.Data["json"] = utils.Export(1000, "查询成功", l)
	}
	c.ServeJSON()
}

// 获取所有用户
// @Title 获取所有
// @Description 获取所有TUser
// @Param	Authorization	header	string	true	" Token"
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.TUser
// @Failure 403
// @router / [get]
func (c *TUserController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	var limit int64 = 10
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("错误: 无效的查询键/值对")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, err := models.GetAllTUser(query, fields, sortby, order, offset, limit)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = l
	}
	c.ServeJSON()
}

// 更新用户信息
// @Title 更新
// @Description 修改密码
// @Param	Authorization	header	string	true	" Token"
// @Param	sn		path 	string	true		"The sn you want to update"
// @Param	body		body 	models.UserPswd	true		"UserPswd"
// @Success 200 {object} models.TUser
// @Failure 403 :id is not int
// @router /updatePswd/:sn [POST]
func (c *TUserController) UpdatePswd() {
	snStr := c.Ctx.Input.Param(":sn")
	var v models.UserPswd

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err != nil {

		c.Data["json"] = utils.Export(1001, "Unmarshal 失败", err.Error())
		c.ServeJSON()
		return
	}
	err := models.UpdatePswd(snStr, v.Oldpswd, v.Newpswd)
	if err != nil {
		c.Data["json"] = utils.Export(1001, "UpdatePswd 失败", err.Error())
		c.ServeJSON()
		return
	}
	c.Data["json"] = utils.Export(1000, "修改密码成功", &v)
	c.ServeJSON()
}

// Post ...
// @Title UpdateInfo
// @Description 修改资料
// @Param	Authorization	header	string	true	" Token"
// @Param	sn		path 	string	true		"The sn you want to update"
// @Param	body		body 	models.TUser	true		"TUser"
// @Success 200 {object} models.TUser
// @Failure 403 :id is not int
// @router /updateInfo/:sn [POST]
func (c *TUserController) UpdateInfo() {
	snStr := c.Ctx.Input.Param(":sn")
	// 从请求体中读取数据
	var v models.TUser
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err != nil {
		c.Data["json"] = utils.Export(1001, "Unmarshal 失败", err.Error())
		c.ServeJSON()
		return
	}
	var err error
	v.Sn = snStr
	if len(v.FaceData) > 0 {
		v.Face, err = utils.UploadBase64(v.FaceData, fmt.Sprintf("/upload/user/%s/", snStr), "face")
		if err != nil {
			c.Data["json"] = utils.Export(1001, " DecodeString FaceData 失败", err.Error())
			c.ServeJSON()
			return
		}
	}
	v.FaceData = ""
	if len(v.YicunData) > 0 {
		v.Yicun, err = utils.UploadBase64(v.YicunData, fmt.Sprintf("/upload/user/%s/", snStr), "yicun")
		if err != nil {
			c.Data["json"] = utils.Export(1001, " DecodeString YicunData 失败", err.Error())
			c.ServeJSON()
			return
		}
	}
	v.YicunData = ""
	if len(v.LiangcunData) > 0 {
		v.Liangcun, err = utils.UploadBase64(v.LiangcunData, fmt.Sprintf("/upload/user/%s/", snStr), "liangcun")
		if err != nil {
			c.Data["json"] = utils.Export(1001, " DecodeString LiangcunData 失败", err.Error())
			c.ServeJSON()
			return
		}
	}
	v.LiangcunData = ""
	err = models.UpdateTUserBySN(&v)
	if err != nil {
		c.Data["json"] = utils.Export(1001, "UpdateTUserById 失败", err.Error())
		c.ServeJSON()
		return
	}
	currentUser, _ := c.Ctx.Input.GetData(utils.CurrentUser).(*utils.UserInfo)
	if currentUser != nil {
		v.Role = currentUser.Role // 保持用户原有的角色不能改。
	}
	c.Data["json"] = utils.Export(1000, "修改资料成功", &v)
	c.ServeJSON()
}

// Delete 删除用户
// @Title Delete
// @Description 注销一个用户
// @Param	Authorization	header	string	true	" Token"
// @Param	sn		path 	string	true		"需要注销的学生sn"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /delete/:sn [delete]
func (c *TUserController) Delete() {
	snStr := c.Ctx.Input.Param(":sn")
	if err := models.DeleteTUser(snStr); err == nil {
		c.Data["json"] = utils.Export(1000, "注销成功", snStr)
	} else {
		c.Data["json"] = utils.Export(1001, "注销失败", snStr)
	}
	c.ServeJSON()
}
